<template>
  <a-menu
    class="new-menu"
    :class="{ 'collapsed-menu': collapsed }"
    mode="inline"
    :open-keys="openKeys"
    @openChange="onOpenChange"
    :inline-collapsed="collapsed"
    :selectedKeys="selectedKeys"
  >
    <template v-for="k in menuShow">
      <template v-if="hasMenuPermission(k)">
        <a-menu-item
          :key="k.name"
          v-if="k.hideChildrenInMenu || !(k.children && k.children.length)"
          @click="jump(k, true)"
        >
          <a-icon :type="k.meta.icon" />
          <a-tooltip :title="k.meta.title" placement="right">
            <span>{{ k.meta.title }}</span>
          </a-tooltip>
        </a-menu-item>
        <a-sub-menu :key="k.name" v-else>
          <span slot="title">
            <a-icon :type="k.meta.icon" />
            <a-tooltip :title="k.meta.title" placement="right">
              <span>{{ k.meta.title }}</span>
            </a-tooltip>
          </span>
          <template v-for="m in k.children">
            <a-menu-item
              :key="m.name"
              v-if="hasMenuPermission(m)"
              @click="jump(m)"
            >
              <!-- <a-icon :type="m.meta.icon" /> -->
              <a-tooltip :title="m.meta.title" placement="right">
                <span>{{ m.meta.title }}</span>
              </a-tooltip>
            </a-menu-item>
          </template>
        </a-sub-menu>
      </template>
    </template>
  </a-menu>
</template>

<script>
import { mapState } from 'vuex'
import store from '@/store'

export default {
  data() {
    return {
      openKeys: [
        'organization',
        'system',
        'SystemLog',
        'SystemNotice',
        'subjectManage'
      ],
      menus: [],
      menuShow: []
    }
  },
  watch: {
    $route(e) {
      this.getMenu()
    }
  },
  computed: {
    ...mapState({
      // 动态主路由
      mainMenu: (state) => state.permission.addRouters,
      collapsed: (state) => state.app.sideCollapsed
    }),
    selectedKeys() {
      // 将它的父级路由也选中
      // return [this.$route.name]
      const routes = this.getSelectedKeys(this.menuShow, [])
      return routes && routes.length ? routes : [this.$route.name]
    }
  },
  created() {
    // const routes = this.mainMenu.find(item => item.path === '/')
    // this.menus = (routes && routes.children) || []
    // const isConfigPage = this.$route.meta?.category === 'config'
    // if (isConfigPage) {
    //   // this.hideAllMenus()
    // } else {
    //   this.handleMenusHiding()
    // }
  },
  mounted() {
    this.getMenu()
  },
  methods: {
    getMenu() {
      const routes = this.mainMenu.find((item) => item.path === '/')
      this.menus = (routes && routes.children) || []
      // const isConfigPage = this.$route.meta?.category === 'config'
      // if (isConfigPage) {
      //   // this.hideAllMenus()
      // } else {
      //   this.handleMenusHiding()
      // }

      if (
        this.menus.findIndex((item) => item.name === this.$route.name) === -1 &&
        this.$route.name !== 'All' &&
        !this.$route.meta.isSystem
      ) {
        const arr = this.handleMenusHiding(this.menus[1].children)
        this.menuShow = arr
          .filter((v) => !v.hidden)
          .map((m) => {
            return {
              ...m,
              children: (m.children || []).filter((n) => !n.meta.hidden)
            }
          })
        return
      }
      // if (!this.$store.state.user.info.isAdmin) {
      //   this.menuShow = this.menus[1].children.filter(v => !v.hidden).map(m => {
      //     return {
      //       ...m,
      //       children: (m.children || []).filter(n => !n.meta.hidden)
      //     }
      //   })
      //   return
      // }

      const arr = this.handleMenusHiding(this.menus)
      const menuArr = arr
        .filter((v) => !v.hidden)
        .map((m) => {
          return {
            ...m,
            children: (m.children || []).filter((n) => !n.meta.hidden)
          }
        })
      this.menuShow = menuArr
    },
    getSelectedKeys(array, selectArray) {
      for (const item of array) {
        const items = JSON.parse(JSON.stringify(selectArray))
        if (item.name === this.$route.name) {
          items.push(item.name)
          return items
        } else if (item.children) {
          items.push(item.name)
          const res = this.getSelectedKeys(item.children, items)
          if (res) {
            return res
          }
        }
      }
    },
    onOpenChange(openKeys) {
      this.openKeys = openKeys
    },
    jump(row, isClose) {
      // isClose && (this.openKeys = [])
      this.$router.push(row.path)
    },
    hasMenuPermission(route) {
      if (
        route.path === '/cost-auditing' &&
        localStorage.getItem('CURRENT_ROLECODE') === 'PROJECT_ADMIN'
      )
        return true
      if (route.meta.isSystem === true && !this.$store.getters.userInfo.isAdmin)
        return false
      if (route.meta.isSystem === false && this.$store.getters.userInfo.isAdmin)
        return false
      return this.menus.some((v) => {
        if (v.name === route.name) return true
        if (v.children) {
          return v.children.some((m) => {
            if (m.name === route.name) return true
            if (m.children) {
              // if (route.name === 'cancelList') {
              //   const isShow = this.$auth('PROJECT.PROJECT_PATIENT_DELETE')
              //   return !!isShow
              // }
              return m.children.some((s) => s.name === route.name)
            }
          })
        }
        return false
      })
    },
    handleMenusHiding(arr) {
      let proId = ''
      const pro = localStorage.getItem('CURRENT_PROID')
      if (pro) {
        proId = parseInt(pro)
      }
      const info = store.getters.userInfo
      arr.forEach((item) => {
        const hiddenItemListWhenNoProject = ['Responsible', 'DataBoard']
        if (hiddenItemListWhenNoProject.includes(item.name)) {
          item.hidden = !proId
        }
        if (item.name === 'organization') {
          item.hidden = proId
        }
        if (item.name === 'system') {
          // item.meta.title = proId ? this.$t('all.autotext374') : this.$t('all.autotext1082')
          item.hidden = !!(info && info.isAdmin === 1 && proId)
        }
        if (item.name === 'SystemLog') {
          // item.meta.title = proId ? this.$t('all.autotext216.1') : this.$t('all.autotext594')
          item.hidden = !!(info && info.isAdmin === 1 && proId)
        }
        if (item.name === 'SystemNotice') {
          item.hidden = !(info && info.isAdmin === 1)
        }
        if (item.name === 'ResearcherList') {
          const isShow =
            this.$auth('PROJECT.PROJECT_FEE') &&
            this.$auth('PROJECT.PROJECT_FEE_RESEARCHER')
          if (proId && isShow) {
            item.hidden = false
          } else {
            item.hidden = true
          }
        }
        if (item.name === 'SubjectList') {
          const isShow =
            this.$auth('PROJECT.PROJECT_FEE') &&
            this.$auth('PROJECT.PROJECT_FEE_PATIENT')
          if (proId && isShow) {
            item.hidden = false
          } else {
            item.hidden = true
          }
        }
        // 受试者管理菜单权限
        if (item.name === 'subjectManage') {
          const isShow = this.$auth('PROJECT.PROJECT_PATIENT')
          if (proId && isShow) {
            item.hidden = false
          } else {
            item.hidden = true
          }
        }
        if (item.name === 'ExpenseAudit') {
          const isShow = this.$auth('PROJECT.PROJECT_FEE_REVIEW')
          if (proId && isShow) {
            item.hidden = false
          } else {
            item.hidden = true
          }
        }
        if (item.name === 'costAuditing') {
          if (proId) {
            item.hidden = true
          } else {
            item.hidden = false
          }
        }
      })
      return arr
    }
  }
}
</script>

<style lang="less" scoped>
.new-menu {
  height: 100%;
  background: #fff;

  ::v-deep {
    .ant-menu-submenu-title {
      padding: 0 16px !important;
    }

    .ant-menu-sub.ant-menu-inline > .ant-menu-item {
      padding: 0 40px !important;
    }
  }
}

.collapsed-menu {
  ::v-deep {
    .ant-menu-submenu-title {
      padding: 0 32px !important;
    }
  }
}
</style>
